package com.ja.openchat.ui.found;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.ja.openchat.BR;
import com.ja.openchat.R;
import com.ja.openchat.adapters.ChooseLocationAdapter;
import com.ja.openchat.data.NotShowPoiItem;
import com.ja.openchat.ui.base.JaBaseActivity;
import com.ja.openchat.views.CustomEditText;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class ChooseLocationActivity extends JaBaseActivity {

    @BindView(R.id.et_search)
    CustomEditText etSearch;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    public final static String[] PERMISSIONS_BASIC = {
            Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION
    };

    public static void chooseLocation(Activity context, int requestCode, PoiItem poiItem) {
        if (!XXPermissions.isGranted(context, ChooseLocationActivity.PERMISSIONS_BASIC)) {
            XXPermissions.with(context).permission(ChooseLocationActivity.PERMISSIONS_BASIC).request(new OnPermissionCallback() {
                @Override
                public void onGranted(List<String> permissions, boolean all) {
                    Intent intent = new Intent(context, ChooseLocationActivity.class);
                    if (poiItem != null) {
                        intent.putExtra("choose", poiItem);
                    }
                    context.startActivityForResult(intent, requestCode);
                }
            });
        } else {
            Intent intent = new Intent(context, ChooseLocationActivity.class);
            if (poiItem != null) {
                intent.putExtra("choose", poiItem);
            }
            context.startActivityForResult(intent, requestCode);
        }
    }

    private ChooseLocationAdapter mAdapter;

    public static final String BUNDLE_RESULT = "location";
    private NotShowPoiItem notShowPoiItem = new NotShowPoiItem();


    private List<PoiItem> poiItemList = new ArrayList<>();


    private LatLng currentLocation;
    private AMapLocationClient locationClient = null;
    private AMapLocationListener mAMapLocationListener;
    private PoiSearch.Query mQuery;
    private PoiSearch mPoiSearch;
    private onPoiSearchLintener mOnPoiSearchListener;

    @Override
    public void initData() {
        setTitle(getString(R.string.choose_location));
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new ChooseLocationAdapter(poiItemList);
        if (getIntent() != null && getIntent().getParcelableExtra("choose") != null) {
            mAdapter.setSelectPoiItem((PoiItem) getIntent().getParcelableExtra("choose"));
        }
        recyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
                Intent intent = new Intent();
                intent.putExtra(BUNDLE_RESULT, mAdapter.getItem(position));
                setResult(Activity.RESULT_OK, intent);
                finish();
            }
        });
        mOnPoiSearchListener = new onPoiSearchLintener();
        mOnGeocodeSearchListener = new GeocodeSearch.OnGeocodeSearchListener() {
            @Override
            public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
                if (i == 1000) {
                    if (regeocodeResult != null) {
                        poiItemList.clear();
                        poiItemList.add(notShowPoiItem);
                        poiItemList.addAll(regeocodeResult.getRegeocodeAddress().getPois());
                        mAdapter.notifyDataSetChanged();
                        recyclerView.smoothScrollToPosition(0);
                    }
                }

            }

            @Override
            public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

            }
        };
        mAMapLocationListener = new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation loc) {
                try {
                    if (null != loc) {
                        stopLocation();
                        if (loc.getErrorCode() == 0) {
                            currentLocation = new LatLng(loc.getLatitude(), loc.getLongitude());
                        }
                        doWhenLocationSucess();
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        };

        etSearch.setOnXTextChangeListener(new CustomEditText.OnXTextChangeListener() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (null != editable) {
                    if (0 == editable.length()) {
//                        refleshSelectByListMark();
                        if (currentLocation != null) {
                            getAddressInfoByLatLong(currentLocation.latitude, currentLocation.longitude);
                        } else {
                            poiItemList.clear();
                            poiItemList.add(notShowPoiItem);
                            mAdapter.notifyDataSetChanged();
                        }
                    } else {
                        if (null != currentLocation) {
                            doSearchQuery(true, editable.toString(), new LatLonPoint(currentLocation.latitude, currentLocation.longitude));
                        } else {
                            doSearchQuery(true, editable.toString(), null);
                        }
                    }
                }
            }
        });

        startLocation();
    }

    private void doWhenLocationSucess() {
        if (currentLocation != null) {
            doSearchQuery(true, "", new LatLonPoint(currentLocation.latitude, currentLocation.longitude));
        } else {
            poiItemList.clear();
            poiItemList.add(notShowPoiItem);
            mAdapter.notifyDataSetChanged();
        }
    }

    private int searchAllPageNum = 1;//Poi搜索最大页数，可应用于上拉加载更多
    private int searchNowPageNum = 1;//当前poi搜索页数

    protected void doSearchQuery(boolean isReflsh, String keyWord, LatLonPoint lpTemp) {
        mQuery = new PoiSearch.Query(keyWord, "", "");//第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
        mQuery.setPageSize(30);// 设置每页最多返回多少条poiitem
        if (isReflsh) {
            searchNowPageNum = 1;
        } else {
            searchNowPageNum++;
        }
        if (searchNowPageNum > searchAllPageNum) {
            return;
        }
        mQuery.setPageNum(searchNowPageNum);// 设置查第一页


        try {
            mPoiSearch = new PoiSearch(this, mQuery);
            mOnPoiSearchListener.IsReflsh(isReflsh);
            mPoiSearch.setOnPoiSearchListener(mOnPoiSearchListener);
            if (lpTemp != null) {
                mPoiSearch.setBound(new PoiSearch.SearchBound(lpTemp, 10000, true));//该范围的中心点-----半径，单位：米-----是否按照距离排序
            }
            mPoiSearch.searchPOIAsyn();// 异步搜索
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private AMapLocationClientOption locationOption = new AMapLocationClientOption();

    public void startLocation() {
        initLocation();
        // 设置定位参数
        locationClient.setLocationOption(locationOption);
        // 启动定位
        locationClient.startLocation();
    }


    private void initLocation() {
        try {
            if (null == locationClient) {
                //初始化client
                locationClient = new AMapLocationClient(this.getApplicationContext());
                //设置定位参数
                locationClient.setLocationOption(getDefaultOption());
                // 设置定位监听
                locationClient.setLocationListener(mAMapLocationListener);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    private AMapLocationClientOption getDefaultOption() {
        AMapLocationClientOption mOption = new AMapLocationClientOption();
        mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
        mOption.setGpsFirst(false);//可选，设置是否gps优先，只在高精度模式下有效。默认关闭
        mOption.setHttpTimeOut(30000);//可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
        mOption.setInterval(2000);//可选，设置定位间隔。默认为2秒
        mOption.setNeedAddress(true);//可选，设置是否返回逆地理地址信息。默认是true
        mOption.setOnceLocation(false);//可选，设置是否单次定位。默认是false
        mOption.setOnceLocationLatest(false);//可选，设置是否等待wifi刷新，默认为false.如果设置为true,会自动变为单次定位，持续定位时不要使用
        AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);//可选， 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
        mOption.setSensorEnable(false);//可选，设置是否使用传感器。默认是false
        mOption.setWifiScan(true); //可选，设置是否开启wifi扫描。默认为true，如果设置为false会同时停止主动刷新，停止以后完全依赖于系统刷新，定位位置可能存在误差
        mOption.setMockEnable(true);//如果您希望位置被模拟，请通过setMockEnable(true);方法开启允许位置模拟
        return mOption;
    }


    private void stopLocation() {
        try {
            if (null != locationClient) {
                locationClient.stopLocation();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private GeocodeSearch.OnGeocodeSearchListener mOnGeocodeSearchListener;

    private void getAddressInfoByLatLong(double latitude, double longitude) {
        try {
            GeocodeSearch geocodeSearch = new GeocodeSearch(this);
            RegeocodeQuery query = new RegeocodeQuery(new LatLonPoint(latitude, longitude), 3000, GeocodeSearch.AMAP);
            geocodeSearch.getFromLocationAsyn(query);
            geocodeSearch.setOnGeocodeSearchListener(mOnGeocodeSearchListener);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    protected boolean isHaveButterKnife() {
        return true;
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_choose_location;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }


    class onPoiSearchLintener implements PoiSearch.OnPoiSearchListener {
        private boolean isReflsh;//是为下拉刷新，否为上拉加载更多

        public void IsReflsh(boolean isReflsh) {
            this.isReflsh = isReflsh;
        }

        @Override
        public void onPoiSearched(PoiResult result, int i) {
            if (i == 1000) {
                if (result != null && result.getQuery() != null) {// 搜索poi的结果
                    searchAllPageNum = Math.max(result.getPageCount(), 1);
                    if (result.getQuery().equals(mQuery)) {// 是否是同一条
                        poiItemList.clear();
                        poiItemList.add(notShowPoiItem);
                        poiItemList.addAll(result.getPois());// 取得第一页的poiitem数据，页数从数字0开始
                        if (mAdapter != null) {
                            mAdapter.notifyDataSetChanged();
                            mAdapter.getLoadMoreModule().loadMoreComplete();
                        }
                        if (isReflsh) {
                            recyclerView.smoothScrollToPosition(0);
                        }

                    }
                }
            }
        }

        @Override
        public void onPoiItemSearched(PoiItem poiItem, int i) {

        }
    }

}
